package com.turing.user.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.turing.common.util.Tools;
import com.turing.user.dao.FunctionPrivilegeMapper;
import com.turing.user.entity.FunctionPrivilege;
import com.turing.user.service.FunctionPrivilegeService;
import com.turing.user.vo.LoginVO;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
* @Description 服务类实现
* @Author livin
* @Date 2022-02-22
*/
@Service
public class FunctionPrivilegeServiceImpl extends ServiceImpl<FunctionPrivilegeMapper, FunctionPrivilege> implements FunctionPrivilegeService {


    @Override
    public boolean checkUserPrivilege(List<Integer> privilegeIds,String url) {
        List<FunctionPrivilege> functionPrivileges = baseMapper.selectList(new LambdaQueryWrapper<FunctionPrivilege>().ne(FunctionPrivilege::getId,privilegeIds));
        if(Tools.isNotEmpty(functionPrivileges)){
            List<String> collect = functionPrivileges.stream().map(FunctionPrivilege::getPrivilegeUrl).collect(Collectors.toList());
            return Tools.isNotEmpty(collect) && collect.contains(url);
        }
        return false;
    }

    @Override
    public List<FunctionPrivilege> getAllPrivilege() {
        return baseMapper.selectList(null);
    }

    @Override
    public List<LoginVO.Menu> buildMenuTree() {

        //查询出所有分类
        List<FunctionPrivilege> entities = baseMapper.selectList(null);

        List<LoginVO.Menu> menuList = entities.stream().map(o->{
            LoginVO.Menu menu = new LoginVO.Menu();
            menu.setId(o.getId());
            menu.setName(o.getEnglishName());
            menu.setPrivilegeName(o.getName());
            menu.setParentId(o.getParentPrivilege());
            return menu;
        }).collect(Collectors.toList());

        //组装成父子的树形结构
        return menuList.stream()
                .filter(o -> o.getParentId() == 0)
                .peek(menu -> menu.setChildNodes(getChildrens(menu, menuList)))
                .collect(Collectors.toList());
    }

    //递归查找所有菜单的子菜单
    private List<LoginVO.Menu> getChildrens(LoginVO.Menu menu,List<LoginVO.Menu> menuList) {
        return menuList.stream()
                .filter( o -> o.getParentId().equals(menu.getId()))
                .peek( o -> {
                    o.setChildNodes(getChildrens(o, menuList));//找到子菜单(递归)
                }).collect(Collectors.toList());
    }
}
